package infra.jenkins.job.template;

import domain.model.project.Project;
import domain.model.project.ProjectType;
import infra.jenkins.JenkinsException;

import java.io.File;

/**
 * @author Gregory Boissinot
 */
public class TemplateRetriever {

    private static final String DEFAULT_TEMPLATE_ID = "default";

    private final String rootTemplateDir;

    public TemplateRetriever(String rootTemplateDir) {
        this.rootTemplateDir = rootTemplateDir;
    }

    public File getTemplateFile(Project project) {
        File templateFile = getComputedTemplateFile(project);
        if (!templateFile.exists()) {
            throw new JenkinsException(String.format("The template file %s must exist.", templateFile));
        }
        return templateFile;
    }

    private File getComputedTemplateFile(Project project) {
        if (project.getTemplateLocalFilePath() != null) {
            return new File(rootTemplateDir, project.getTemplateLocalFilePath());
        }

        File templateDir = new File(rootTemplateDir, getTemplateId(project));
        if (!templateDir.exists()) {
            throw new JenkinsException(String.format("The template dir %s must exist.", templateDir));
        }
        File templateFile = new File(templateDir, "templateJob.vm");

        return templateFile;
    }

    private String getTemplateId(Project project) {
        ProjectType projectType = project.getProjectType();
        if (projectType == null) {
            return DEFAULT_TEMPLATE_ID;
        }

        return projectType.getName();
    }
}
